<template>
  <div class="tags">
    <el-card>
      <!-- 面包屑导航 -->
      <div v-if="this.$route.query.name" slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ this.$route.query.name }}</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 搜索表单 -->
      <el-form ref="form" :inline="true" :model="form" label-width="5rem">
        <el-form-item label="标签名称" prop="tagName">
          <el-input
            v-model.trim="form.tagName"
            placeholder="根据标签名称搜索"
            @input="tagNamgeInput"
          />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select
            v-model="form.state"
            placeholder="请选择"
            @change="stateChange"
          >
            <el-option label="已启用" value="1" />
            <el-option label="已禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetFields">清除</el-button>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-form-item>
        <el-button
          class="fr"
          type="success"
          icon="el-icon-edit"
          @click="addDialog"
        >新增标签</el-button>
        <el-button
          v-if="this.$route.query.id"
          type="text"
          class="fr"
          icon="el-icon-back"
          @click="back"
        >返回学科</el-button>
      </el-form>
      <!-- 共计多少条数据 -->
      <el-alert :title="'数据一共' + counts + '条'" type="info" show-icon />
      <!-- 标签列表 -->
      <el-table :data="subjectsListAll" stripe style="width: 100%">
        <el-table-column
          prop="id"
          label="序号"
          width="180"
          type="index"
          :index="pagesize * (page - 1) + 1"
        />
        <el-table-column prop="subjectName" label="所属学科" width="180" />
        <el-table-column prop="tagName" label="标签名称" />
        <el-table-column prop="username" label="创建者" />
        <el-table-column prop="addDate" label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.addDate | dateFormat("YYYY-mm-dd HH:MM:SS") }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            <!-- <i class="el-icon-time"></i> -->
            <span style="margin-left: .625rem">{{
              scope.row.state ? "已启用" : "已禁用"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="changeState(scope.row.state, scope.row.id)"
            >{{ !scope.row.state ? "启用" : "禁用" }}</el-button>
            <el-button
              type="text"
              :disabled="!scope.row.state"
              @click="modDialog(scope.row.id)"
            >修改</el-button>
            <el-button
              type="text"
              :disabled="!scope.row.state"
              @click="delTags(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end">
        <el-pagination
          :current-page="page"
          background
          :page-sizes="[5, 10, 20, 50]"
          :page-size="10"
          layout="prev, pager, next, sizes, jumper"
          :total="counts"
          @current-change="currentChange"
          @size-change="sizeChange"
        />
      </el-row>
    </el-card>
    <!-- 新增标签弹出框 -->
    <el-dialog title="新增标签" :visible.sync="dialogVisibleAdd" width="20%">
      <el-form ref="addform" :rules="rules" :model="addform" label-width="5rem">
        <el-form-item
          v-if="!this.$route.query.id"
          label="所属学科"
          prop="subjectID"
        >
          <el-select v-model="addform.subjectID" placeholder="请选择">
            <el-option
              v-for="item in subjectsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model.trim="addform.tagName" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAdd = false">取 消</el-button>
        <el-button type="primary" @click="addTages">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改标签弹出框 -->
    <el-dialog title="修改标签" :visible.sync="dialogVisibleMod" width="20%">
      <el-form ref="modform" :rules="rules" :model="modform" label-width="5rem">
        <el-form-item
          v-if="!this.$route.query.id"
          label="所属学科"
          prop="subjectID"
        >
          <el-select v-model="modform.subjectID" placeholder="请选择">
            <el-option
              v-for="item in subjectsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model.trim="modform.tagName" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleMod = false">取 消</el-button>
        <el-button type="primary" @click="modTages">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author: zhanglei
 * @Date: 2020-11-7 11:55:49
 * @Last Modified by: zhanglei
 * @Last Modified time: 2020-11-7 12:17:34
 * 标签
 */
// 引入日期格式化工具
import dateFormat from '@/utils/dateFormat.js'
// 引入封装好的接口
import {
  list,
  add,
  changeState,
  remove,
  detail,
  update
} from '@/api/tags.js'
import { simple as simpleSubjects } from '@/api/subjects.js'
export default {
  name: 'Tags',
  filters: {
    // 格式化日日期
    dateFormat(val, format) {
      const date = new Date(val)
      return dateFormat(format, date)
    }
  },
  data() {
    return {
      // val: '',
      // 定时器
      timer: null,
      // 学科列表数据
      subjectsListAll: [],
      // 学科简单列表数据
      subjectsList: [],
      // 新增目录的表单验证
      rules: {
        tagName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      // 新增表单数据
      addform: {
        subjectID: '',
        tagName: ''
      },
      // 修改表单数据
      modform: {
        id: '',
        subjectID: null,
        tagName: ''
      },
      dialogVisibleAdd: false, // 新增目录弹框
      dialogVisibleMod: false,
      // 搜索表单数据
      form: {
        tagName: null,
        state: null
      },
      subjectID: this.$route.query.id || null,
      page: 1, // 第几页
      pagesize: 10, // 一页几条数据
      counts: 0 // 一共多少条
    }
  },
  watch: {
    // 监听 $router 变化重新渲染列表数据
    $route(val) {
      this.subjectID = val.query.id || null
      this.getTags()
    }
  },
  created() {
    this.getTags()
    // this.getpush()
  },
  methods: {
    // getpush() {
    //   this.val = this.$route.query.name
    //   console.log(this.val)
    // },
    // 搜索框失去焦点事件
    tagNamgeInput() {
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        console.log('定时器执行了')
        this.getTags()
        this.timer = null
      }, 500)
    },
    stateChange() {
      this.getTags()
    },
    // 状态框改变事件
    // 返回学科
    back() {
      this.$router.push('/details')
    },
    // 切换页码, 重新请求数据
    currentChange(currentPage) {
      this.page = currentPage
      this.getTags()
    },
    sizeChange(pagesize) {
      console.log(pagesize)
      this.pagesize = pagesize
      this.getTags()
    },
    // 点击确认修改
    modTages() {
      let flag
      this.$refs.modform.validate(valid => {
        flag = valid
      })
      if (!flag) return
      try {
        const res = update(this.modform)
        console.log(res)
        this.$message.success('修改成功')
        this.getTags()
        this.dialogVisibleMod = false
      } catch (error) {
        this.$message.error('修改失败')
        this.dialogVisibleMod = false
      }
    },
    // 修改标签弹框
    async modDialog(id) {
      this.dialogVisibleMod = true
      this.modform.id = id
      try {
        const res = await detail({ id })
        console.log('标签详情', res)
        this.modform = res.data
      } catch (error) {
        console.log(error)
      }
      try {
        const res = await simpleSubjects()
        console.log('学科简单列表', res)
        this.subjectsList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 删除标签
    delTags(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            const res = await remove({
              id
            })
            console.log('删除标签', res)
            this.$message.success('删除成功')
            this.getTags()
          } catch (error) {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 切换标签状态
    async changeState(state, id) {
      const data = {}
      data.id = id
      data.state = state ? 0 : 1
      console.log(data)
      this.getTags()
      try {
        const res = await changeState(data)
        console.log('切换文章状态', res)
      } catch (error) {
        console.log(error)
      }
    },
    // 点击新增标签
    async addTages() {
      this.dialogVisibleAdd = false
      if (!this.addform.subjectID) this.addform.subjectID = 0
      try {
        const res = await add(this.addform)
        console.log(res)
        console.log('新增标签', res)
        this.$message.success('添加成功')
        this.getTags()
        this.$refs.addform.resetFields()
        // this.addform.subjectID = null
      } catch (error) {
        this.$message.error('添加失败')
        console.log(error)
        this.dialogVisibleAdd = false
      }
    },
    // 新增标签弹框
    async addDialog() {
      this.dialogVisibleAdd = true
      try {
        const res = await simpleSubjects()
        console.log('学科简单列表', res)
        this.subjectsList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取标签列表
    async getTags() {
      const page = this.page
      const pagesize = this.pagesize
      const subjectID = this.subjectID
      const { tagName, state } = this.form
      console.log(state, tagName)
      try {
        const res = await list({
          page,
          pagesize,
          subjectID,
          tagName,
          state
        })
        console.log('标签列表', res)
        this.subjectsListAll = res.data.items
        this.counts = res.data.counts
      } catch (error) {
        console.log(error)
      }
    },
    // 搜索按钮方法
    // 清空表单按钮方法
    resetFields() {
      this.$refs.form.resetFields()
      this.getTags()
    },
    // 搜索按钮方法
    search() {
      this.page = 1
      this.getTags()
    }
    // 页面跳转，根据id展示数据详情
    // async getTagsById() {
    //   const subjectID = this.$route.query.id
    //   console.log(subjectID)
    //   const { data } = await getTagsById({
    //     ...defaultItem,
    //     subjectID
    //   })
    //   this.tableData = data.items
    //   this.page.total = data.counts
    // }
  }
}
</script>
<style scoped lang="scss">
.tags {
  ::v-deep .el-dialog {
    border-radius: 10px;
    overflow: hidden;
    .el-dialog__header {
      background-color: #409eff;
      .el-dialog__title {
        color: #fff;
      }
      .el-icon-close:before {
        color: #fff;
      }
    }
    .el-dialog__body {
      margin-bottom: -20px;
      margin-left: 20px;
      // .el-form-item__label {
      //   width: 230px !important;
      // }
    }
    .el-dialog__footer {
      padding-top: 0 !important;
      .btnOk {
        margin-right: 60px;
      }
    }
  }
}

.dashboard-container {
  ::v-deep .el-dialog {
    border-radius: 10px;
    overflow: hidden;
    .el-dialog__header {
      background-color: #409eff;
      .el-dialog__title {
        color: #fff;
      }
      .el-icon-close:before {
        color: #fff;
      }
    }
    .el-dialog__body {
      margin-bottom: -20px;
      margin-left: 20px;
      // .el-form-item__label {
      //   width: 230px !important;
      // }
    }
    .el-dialog__footer {
      padding-top: 0 !important;
      .btnOk {
        margin-right: 60px;
      }
    }
  }
}
</style>
<style scoped lang="less">
.tags {
  /deep/ .el-dialog__footer {
    text-align: right;
  }
  .fr {
    margin-left: 0.625rem;
  }
}
</style>
